package com.hao.nettyrpc.transport.netty.server;

import com.hao.nettyrpc.code.CommonDecoder;
import com.hao.nettyrpc.code.CommonEncoder;
import com.hao.nettyrpc.provider.ServiceProviderImpl;
import com.hao.nettyrpc.serializer.CommonSerializer;
import com.hao.nettyrpc.serializer.KryoSerializer;
import com.hao.nettyrpc.transport.AbstractRpcServer;
import com.hao.nettyrpc.registry.NacosServiceRegistry;
import com.hao.nettyrpc.hook.ShutdownHook;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/4/11 12:43
 */
public class NettyServer extends AbstractRpcServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);


    private final CommonSerializer serializer;


    public NettyServer(String host, int port) {
        this(host,port,DEFAULT_SERIALIZER);
    }
    public NettyServer(String host, int port,Integer serializer) {
        this.port = port;
        this.host = host;
        serviceProvider = new ServiceProviderImpl();
        serviceRegistry = new NacosServiceRegistry();
        this.serializer = CommonSerializer.getByCode(serializer);
        scanServices();
    }

    @Override
    public void start() {
        ShutdownHook.getShutdownHook().addClearAllHook();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //设置 半连接  和 全连接队列长队
                    .option(ChannelOption.SO_BACKLOG,256)
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    //禁止使用  Nagle算法(该算法会将  小的数据包组装成大的数据包然后一起发送  会造成延时)
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(30,0,0, TimeUnit.SECONDS));
                            //pipeline.addLast(new CommonEncoder(new JsonSerializer()));//添加编码器
                            pipeline.addLast(new CommonEncoder(new KryoSerializer()));
                            pipeline.addLast(new CommonDecoder());//添加解码器
                            pipeline.addLast(new NettyServerHandle());//添加自定义处理器
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(host,port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("启动服务器时有错误发生",e);
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
